package app.system;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.net.URI;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
/**
 * This class read a URL (a file uri in this case) and return a JScrollPane that displays the file content.
 * @author j55wu
 *
 */
public class TextLoader {

	private boolean windows;
	public TextLoader(boolean platformIsWindows){
		//true if windows
		this.windows = platformIsWindows;
	}
	
	private URL getRelativePath(String given){
		File file = new File("myTestPathFile");
		String abs = file.getAbsolutePath();
		if(windows){
			abs = abs.substring(0, abs.lastIndexOf("\\")) + "\\" + given;
		}else{
			abs = "file:" + abs.substring(0, abs.lastIndexOf("/")) + "/" + given;
		}
		//System.out.println(TextLoader.class.getResource("").getPath());
		URL ret = null;
		try {
			ret =  new URI(abs).toURL();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	public JScrollPane loadTextToJPane(String file){
		JEditorPane editorPane = new JEditorPane();
		editorPane.setEditable(false);
		URL syntaxURL = this.getRelativePath(file);
		if (syntaxURL != null) {
		    try {
		        editorPane.setPage(syntaxURL);
		    } catch (Exception e) {
		        System.err.println("Attempted to read a bad URL: " + syntaxURL);
		    }
		} else {
		    System.err.println("Couldn't find file: " + syntaxURL);
		}

		//Put the editor pane in a scroll pane.
		JScrollPane editorScrollPane = new JScrollPane(editorPane);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		editorScrollPane.setVerticalScrollBarPolicy(
		                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		editorScrollPane.setPreferredSize(new Dimension(screenSize.width/2, screenSize.height/2));
		editorScrollPane.setMinimumSize(new Dimension(10, 40));
		return editorScrollPane;
	}
}
